package cn.lhf.cd.controller;

import cn.lhf.cd.FXApplication;
import cn.lhf.cd.Main;
import cn.lhf.cd.annotation.FXController;
import cn.lhf.cd.domain.OrderModel;
import cn.lhf.cd.entity.Order;
import cn.lhf.cd.entity.User;
import cn.lhf.cd.mapper.OrderMapper;
import cn.lhf.cd.mapper.UserMapper;
import javafx.beans.property.ReadOnlyStringWrapper;
import javafx.collections.FXCollections;
import javafx.event.ActionEvent;
import javafx.fxml.Initializable;
import javafx.scene.control.*;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.text.Font;
import javafx.scene.text.Text;
import org.apache.ibatis.session.SqlSession;

import java.net.URL;
import java.util.ArrayList;
import java.util.ResourceBundle;

@FXController(path = "/ui/user_home.fxml")
public class UserHomeController implements Initializable {
    public ToggleGroup toggle;
    public TextField nameField;
    public TextField phoneField;
    public TextField addressField;
    public RadioButton manRadio;
    public RadioButton womanRadio;
    public TableView<OrderModel> tableView;
    public TableColumn serialNumCol;
    public TableColumn idCol;
    public TableColumn dateCol;
    public TableColumn nameCol;
    public TableColumn infoCol;

    private User self;
    private boolean onlyRead = true;

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        FXApplication.setTitle("个人中心");

        //初始状态禁止编辑信息
        nameField.setDisable(true);
        phoneField.setDisable(true);
        addressField.setDisable(true);
        manRadio.setDisable(true);
        womanRadio.setDisable(true);

        //从数据库读取订单信息
        SqlSession sqlSession = Main.openSqlSession();
        ArrayList<OrderModel> items = new ArrayList<>();
        for (Order order : sqlSession.getMapper(OrderMapper.class).getAll()) {
            items.add(order.toModel());
        }
        sqlSession.close();
        tableView.setItems(FXCollections.observableList(items));

        //绑定各列在模型中的字段
        serialNumCol.setCellValueFactory(new PropertyValueFactory<>("serialNum"));
        idCol.setCellValueFactory(new PropertyValueFactory<>("id"));
        dateCol.setCellValueFactory(new PropertyValueFactory<>("date"));
        nameCol.setCellValueFactory(new PropertyValueFactory<>("name"));


        //设置商品名的字体大小
        nameCol.setCellFactory(param -> {
            TableCell cell = new TableCell<>();
            Text text = new Text();
            text.setFont(new Font(18));
            cell.setGraphic(text);
            cell.setPrefHeight(Control.USE_COMPUTED_SIZE);  //自适应高度
            text.wrappingWidthProperty().bind(cell.widthProperty());
            text.textProperty().bind(cell.itemProperty());
            return cell;
        });

        //设置收件信息的生成方式
        infoCol.setCellValueFactory(param -> new ReadOnlyStringWrapper(String.format("%s %s %s", self.getAddress(),
                self.getName(), self.getPhone())));
        //设置收件信息的字体大小
        infoCol.setCellFactory(param -> {
            TableCell cell = new TableCell<>();
            Text text = new Text();
            text.setFont(new Font(18));
            cell.setGraphic(text);
            cell.setPrefHeight(Control.USE_COMPUTED_SIZE);  //自适应高度
            text.wrappingWidthProperty().bind(cell.widthProperty());
            text.textProperty().bind(cell.itemProperty());
            return cell;
        });
    }

    public void onChangeStatusOrSaveInfo(ActionEvent event) {
        if (onlyRead) { //初始状态是只读，这个时候要让它可编
            nameField.setDisable(false);
            phoneField.setDisable(false);
            addressField.setDisable(false);
            manRadio.setDisable(false);
            womanRadio.setDisable(false);
            onlyRead = false;

            Button button = (Button) event.getSource();
            button.setText("保存");
        } else {    //如果已经是可编辑状态，就保存资料到数据库
            getContentToSelf();
            SqlSession sqlSession = Main.openSqlSession();
            sqlSession.getMapper(UserMapper.class).save(self);
            sqlSession.commit();
            sqlSession.close();
            tableView.refresh();
        }
    }

    /**
     * 从self获取信息
     */
    public void setContentFromSelf() {
        nameField.setText(self.getName());
        phoneField.setText(self.getPhone());
        addressField.setText(self.getAddress());
        toggle.selectToggle("男".equals(self.getSex()) ? manRadio : womanRadio);
    }

    /**
     * 保存信息至self
     */
    public void getContentToSelf() {
        self.setName(nameField.getText());
        self.setPhone(phoneField.getText());
        self.setAddress(addressField.getText());
        self.setSex(((RadioButton) toggle.getSelectedToggle()).getText());
    }

    public void setSelf(User self) {
        this.self = self;
    }
}
